package com.example.ktapplication.fragment

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.adapter.RvResultAdapter
import com.example.ktapplication.base.BaseTitleRvFragment
import com.example.ktapplication.bean.FindArticleDataX
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.SystemViewModel
import com.example.ktapplication.utils.LogHelper
import com.example.ktapplication.utils.jumpUrl
import com.example.ktapplication.utils.toJson

class BlogListFragment(private val cid: Int, private val blogType: Int = BLOG_REQ_SYS) :
    BaseTitleRvFragment() {

    companion object {
        const val BLOG_REQ_SYS = 0
        const val BLOG_REQ_PROJECT = 1
    }

    private val viewModel by lazy {
        ViewModelProvider(this)[SystemViewModel::class.java]
    }

    private val blogAdapter by lazy {
        RvResultAdapter(requireActivity()).apply {
            setItemClickListener(object : RvResultAdapter.OnItemClickListener {
                override fun onCollectClick(item: FindArticleDataX) {
                    val id = item.id
                    if (item.collect) {
                        viewModel.unCollect(id) {
                            updateItem(item.apply { collect = false })
                        }
                    } else {
                        viewModel.collect(id) {
                            updateItem(item.apply { collect = true })
                        }
                    }
                }

                override fun onBodyClick(item: FindArticleDataX) {
                    item.let {
                        requireActivity().jumpUrl(it.link, it.title)
                    }
                }
            })
        }
    }

    override fun initAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder> {
        return blogAdapter
    }

    override fun onDate(savedInstanceState: Bundle?) {
        viewModel.sysBlogData.observe(this) {
            LogHelper.e("---ext ${javaClass.simpleName} sysBlogData >>> ${it.toJson()}")
            blogAdapter.setData(it.datas)
            loadDataFinish()
        }
        viewModel.addViewModelState {
            if (it != StateLayoutMode.CONTENT) {
                blogAdapter.setData(mutableListOf())
                loadDataFinish()
            }
        }
    }

    override fun loadData() {
//        showDialog("加载中...", "systemList")
        if (blogType == BLOG_REQ_SYS) {
            viewModel.getSysBlog(cid)
        } else if (blogType == BLOG_REQ_PROJECT) {
            viewModel.getProjectBlog(cid)
        }
    }

    override fun loadMoreData() {
        loadDataFinish()
    }

}
